package cn.tjad.tjad2.module.document.widget;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.utils.AppUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.pictureselect.TJBaseAdapter;
import cn.tjad.tjad2.module.common.pictureselect.ViewHolder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class DocumentOperatorPanel extends LinearLayout implements View.OnClickListener, AdapterView.OnItemClickListener {

    public static final int OP_DOWNLOAD = 0;
    public static final int OP_DELETE = 1;
    public static final int OP_SHARE = 2;
    public static final int OP_RENAME = 3;
    public static final int OP_MORE = 4;
    public static final int OP_VIEW = 5;
    public static final int OP_OPEN = 6;
    public static final int OP_OPEN_ONLINE = 7;
    public static final int OP_MOVE = 8;
    public static final int OP_SET_LINK = 9;
    public static final int OP_PERMISSION = 10;
    public static final int OP_HOSTORY = 11; //查看历史版本

    private PopupWindow popupMenu;
    private PopMenuAdapter popMenuAdapter;
    private final List<DocumentOperateEntity> moreItems = new ArrayList<>();

    private final List<DocumentOperateEntity> operateEntityList = new ArrayList<>();
    private final List<Integer> fixedItems = Arrays.asList(OP_DOWNLOAD, OP_DELETE, OP_SHARE, OP_RENAME, OP_MORE);
    private List<TextView> textViews = new ArrayList<>();

    private OnFileOperateListener onFileOperateListener;
    private int type = 0; //0=项目文档  1=我的文档  2=回收站


    public DocumentOperatorPanel(@NonNull Context context) {
        this(context, null);
    }

    public DocumentOperatorPanel(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initData();
        init();
    }

    private void initData() {
        operateEntityList.add(new DocumentOperateEntity(OP_DOWNLOAD, "下载", R.drawable.icon_download));
        operateEntityList.add(new DocumentOperateEntity(OP_DELETE, "删除", R.drawable.icon_delete_file));
        operateEntityList.add(new DocumentOperateEntity(OP_SHARE, "分享", R.drawable.icon_share));
        operateEntityList.add(new DocumentOperateEntity(OP_RENAME, "重命名", R.drawable.icon_rename));
        operateEntityList.add(new DocumentOperateEntity(OP_MORE, "更多", R.drawable.icon_more));
        operateEntityList.add(new DocumentOperateEntity(OP_VIEW, "预览", R.mipmap.icon_open));
        operateEntityList.add(new DocumentOperateEntity(OP_OPEN, "打开", R.mipmap.icon_open));
        operateEntityList.add(new DocumentOperateEntity(OP_OPEN_ONLINE, "在线预览", R.mipmap.icon_open_online));
        operateEntityList.add(new DocumentOperateEntity(OP_MOVE, "移动", R.mipmap.icon_move));
        operateEntityList.add(new DocumentOperateEntity(OP_SET_LINK, "链接", R.mipmap.icon_link));
        operateEntityList.add(new DocumentOperateEntity(OP_PERMISSION, "权限", R.mipmap.icon_link));
        operateEntityList.add(new DocumentOperateEntity(OP_HOSTORY, "历史版本", R.mipmap.icon_link));
    }

    private void init() {
        setOrientation(HORIZONTAL);
        for (int i = 0; i < fixedItems.size(); i++) {
            DocumentOperateEntity entity = operateEntityList.get(fixedItems.get(i));
            TextView textView = getTextView(entity.id, entity.text, entity.imageId);
            textView.setEnabled(true);
            textView.setTextColor(AppUtils.getColorStateList(R.color.file_operate_text_color));
            LinearLayout.LayoutParams lp = new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.weight = 1;
            addView(textView, lp);
        }
    }


    private TextView getTextView(int op_id, String text, int imageId) {
        TextView textView = new TextView(getContext());
        textView.setText(text);
        textView.setCompoundDrawablesWithIntrinsicBounds(0, imageId, 0, 0);
        textView.setGravity(Gravity.CENTER);
        textView.setTag(op_id);
        textView.setOnClickListener(this);
        return textView;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void showPanelFor(FileBean fileBean) {
        if (fileBean == null) {
            return;
        }
        Observable.fromIterable(operateEntityList)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(documentOperateEntity -> {
                    documentOperateEntity.show = true;
                    documentOperateEntity.enable = true;
                })
                .doOnComplete(() -> {
                    if (fileBean.directory) {
                        if (type != 2) {
                            operateEntityList.get(OP_DOWNLOAD).enable = false;
                            operateEntityList.get(OP_VIEW).show = false;
                            operateEntityList.get(OP_OPEN).show = false;
                            operateEntityList.get(OP_OPEN_ONLINE).show = false;
                            operateEntityList.get(OP_SET_LINK).show = false;
                            operateEntityList.get(OP_HOSTORY).show = false;
                        } else {
                            operateEntityList.get(OP_DOWNLOAD).enable = false;
                            operateEntityList.get(OP_VIEW).show = false;
                            operateEntityList.get(OP_OPEN).show = false;
                            operateEntityList.get(OP_OPEN_ONLINE).show = false;
                            operateEntityList.get(OP_SET_LINK).show = false;
                            operateEntityList.get(OP_PERMISSION).show = false;
                            operateEntityList.get(OP_HOSTORY).show = false;
                        }
                    } else if (isRvtFile(fileBean.name)) {
                        operateEntityList.get(OP_OPEN).show = false;
                        operateEntityList.get(OP_OPEN_ONLINE).show = false;
                        operateEntityList.get(OP_PERMISSION).show = false;
                    } else if (fileBean.document != null && "0".equals(fileBean.document.forgeStatus)) {
                        operateEntityList.get(OP_OPEN).show = false;
                        operateEntityList.get(OP_OPEN_ONLINE).show = false;
                        operateEntityList.get(OP_PERMISSION).show = false;
                        operateEntityList.get(OP_SET_LINK).show = false;
                    } else {
                        operateEntityList.get(OP_OPEN_ONLINE).show = false;
                        operateEntityList.get(OP_PERMISSION).show = false;
                        operateEntityList.get(OP_SET_LINK).show = false;
                    }
                    openPanel();
                })
                .subscribe();
    }

    public void showPanelFor(List<FileBean> fileList) {
        if(fileList != null || fileList.size() > 0) {
            if (fileList.size() == 1) {
                showPanelFor(fileList.get(0));
            } else {
                Observable.fromIterable(operateEntityList)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnNext(documentOperateEntity -> {
                            documentOperateEntity.show = true;
                            documentOperateEntity.enable = true;
                        })
                        .doOnComplete(() -> {
                            operateEntityList.get(OP_DOWNLOAD).enable = false;
                            operateEntityList.get(OP_RENAME).enable = false;
                            operateEntityList.get(OP_OPEN).show = false;
                            operateEntityList.get(OP_OPEN_ONLINE).show = false;
                            operateEntityList.get(OP_PERMISSION).show = false;
                            operateEntityList.get(OP_SET_LINK).show = false;
                            operateEntityList.get(OP_VIEW).show = false;
                            operateEntityList.get(OP_HOSTORY).show = false;
                            openPanel();
                        })
                        .subscribe();
            }

        }
    }

    private void openPanel() {
        Observable.fromIterable(Arrays.asList(0,1,2,3,4))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(i -> {
                    DocumentOperateEntity entity = operateEntityList.get(i);
                    TextView textView = (TextView) getChildAt(i);
                    textView.setEnabled(entity.enable);
                }).doOnComplete(() -> setVisibility(VISIBLE)).subscribe();
    }

    @Override
    public void onClick(View view) {
        int op_id = (int) view.getTag();
        boolean result = true;
        if (op_id == OP_MORE) {
            onMoreClicked(view);
            return;
        }
        if (onFileOperateListener != null) {
            result = onFileOperateListener.onFileOperate(op_id);
        }
        if (result) {
            setVisibility(GONE);
        }
    }

    private void onMoreClicked(View moreView) {
        if (popupMenu == null) {
            initPopMenu();
        }
        moreItems.clear();
        Observable.fromIterable(operateEntityList)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(documentOperateEntity -> operateEntityList.indexOf(documentOperateEntity) >= 5)
                .filter(documentOperateEntity -> documentOperateEntity.show)
                .doOnNext(documentOperateEntity -> moreItems.add(documentOperateEntity))
                .doOnComplete(() -> {
                    popMenuAdapter.notifyDataSetChanged();
                    int[] location = new int[2];
                    moreView.getLocationOnScreen(location);
                    int yOffset = Tools.getScreenSize(getContext())[1] - location[1];
                    popupMenu.showAtLocation(moreView, Gravity.BOTTOM|Gravity.RIGHT, -10, yOffset);
                }).subscribe();
    }

    private void initPopMenu() {
        popupMenu = new PopupWindow(getContext());
        popupMenu.setWidth(300);
        popupMenu.setOutsideTouchable(true);
        popupMenu.setTouchable(true);
        popupMenu.setBackgroundDrawable(new ColorDrawable());
        ListView listView = new ListView(getContext());
        listView.setOnItemClickListener(this);
        popMenuAdapter = new PopMenuAdapter(getContext(), moreItems);
        listView.setAdapter(popMenuAdapter);
        listView.setBackgroundResource(R.drawable.sort_window_bg);
        popupMenu.setContentView(listView);
    }

    public void setOnFileOperateListener(OnFileOperateListener onFileOperateListener) {
        this.onFileOperateListener = onFileOperateListener;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DocumentOperateEntity entity = (DocumentOperateEntity) popMenuAdapter.getItem(position);
        if (onFileOperateListener != null) {
            onFileOperateListener.onFileOperate(entity.id);
        }
        popupMenu.dismiss();
    }

    public interface OnFileOperateListener {
        boolean onFileOperate(int id);
    }

    private boolean isRvtFile(String fileName) {
        if (fileName == null) {
            return false;
        }
        return fileName.endsWith(".rvt") || fileName.endsWith(".RVT");
    }

    public static class DocumentOperateEntity {
        public int id;
        public String text;
        public int imageId;
        public boolean show;
        public boolean enable;

        public DocumentOperateEntity(int id, String text, int imageId) {
            this(id, text, imageId, true, true);
        }

        public DocumentOperateEntity(int id, String text, int imageId, boolean show, boolean enable) {
            this.id = id;
            this.text = text;
            this.imageId = imageId;
            this.show = show;
            this.enable = enable;
        }
    }

    static class PopMenuAdapter extends TJBaseAdapter {

        public PopMenuAdapter(Context context, List data) {
            super(context, data);
        }

        @Override
        public ViewHolder getViewHolder(int position) {
            return new PopMenuViewHolder(context);
        }

        static class PopMenuViewHolder extends ViewHolder<DocumentOperateEntity> {

            @BindView(R.id.pop_menu_item_text)
            TextView textView;
            public PopMenuViewHolder(Context context) {
                super(context);
                ButterKnife.bind(this, itemView);
            }

            @Override
            public void setValue(DocumentOperateEntity documentOperateEntity, int position) {
                textView.setText(documentOperateEntity.text);
            }

            @Override
            public int getLayoutId() {
                return R.layout.pop_menu_item;
            }
        }
    }
}
